package cn.thoughtworks.school.training.todos.controller;

import cn.thoughtworks.school.training.todos.entity.Todo;
import cn.thoughtworks.school.training.todos.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    TodoRepository todoRepository;

    @GetMapping
    public Page<Todo> getTodos() {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(0, 20, sort);

        return todoRepository.findAll(pageable);
    }

    @PostMapping
    public Todo createTodo() {
        Todo todo = Todo.builder()
                .text("abc")
                .complete(false)
                .createTime(LocalDate.now())
                .build();

        todoRepository.save(todo);
        return todo;
    }
}
